package com.anc.platform.utils;

import com.anc.redis.redis.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import util.LocalDateTimeUtil;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * @author: Anc
 * @date: 2021/7/9 下午4:11
 * @description: 单号生成工具类
 */
@Component
public class CodeUtil {

    @PostConstruct
    public void init() {
        staticRedisClient = this.redisClient;
    }


    private static RedisClient staticRedisClient;

    @Autowired
    private RedisClient redisClient;

    /**
     * 广告位code
     */
    public static final String GGW = "GGW";
    /**
     * 商品池
     */
    public static final String SPC = "SPC";

    /**
     * 页签code
     */
    public static final String YQ = "YQ";

    /**
     * 轮播 code
     */
    public static final String BN = "BN";

    /**
     * 魔方 code
     */
    public static final String MF = "MF";
    /**
     * 公告code
     */
    public static final String GG = "GG";
    /**
     * 频道code
     */
    public static final String PD = "PD";
    /**
     * 主题code
     */
    public static final String EJLM = "EJLM";

    /**
     * 类目域code
     */
    public static final String LMY = "LMY";

    /**
     * 类目code
     */
    public static final String LM = "LM";

    /**
     * app更新提醒code
     */
    public static final String GXTS = "GXTS";

    /**
     * 新人专区
     */
    public static final String XRZQ = "XRZQ";

    /**
     * 弹窗配置
     */
    public static final String TC = "TC";

    /**
     * 获取code 格式如DYCXXX
     *
     * @param prefix 编号前缀
     * @param length 数字长度，不够补0,必须大于0
     * @return
     */
    public static String upNormalCode(String prefix, int length) {
        long num = staticRedisClient.increment(prefix, 1);
        if (length < 1) {
            length = 1;
        }
        return String.format("%s%0" + length + "d", prefix, num);
    }

    /**
     * 获取code 格式如FCED20210001
     *
     * @param prefix
     * @return
     */
    public static String upCode(String prefix) {
        return upYMDCode(prefix, 4);
    }

    /**
     * 获取code 格式如FCED2021XXX
     *
     * @param prefix 编号前缀
     * @param length 数字长度，不够补0,必须大于0
     * @return
     */
    public static String upYMDCode(String prefix, int length) {
        LocalDateTime currentDateTime = LocalDateTimeUtil.getCurrentDateTime();
        String key = prefix + LocalDateTimeUtil.parseDatetimeByFormat(currentDateTime, LocalDateTimeUtil.TimeFormat.SHORT_DATE_PATTERN_NONE);
        long num = staticRedisClient.increment(key, 1);
        // 时间为1天
        staticRedisClient.expire(key, 1, TimeUnit.DAYS);
        if (length < 1) {
            length = 1;
        }
        return String.format("%s%0" + length + "d", key, num);
    }
}
